<!--检测方案的首页-->
<template>
  <div class="index-container">
    <!-- 搜索条件区域 -->
    <div class="search-box">
      <div class="search-item">
        <span class="search-label">方案编号</span>
        <el-input
          v-model="searchQuery.template_code"
          placeholder="请输入方案编号"
        ></el-input>
      </div>

      <div class="search-item">
        <span class="search-label">方案名称</span>
        <el-input
          v-model="searchQuery.template_name"
          placeholder="请输入方案名称"
        ></el-input>
      </div>
      
      <div class="search-item">
        <span class="search-label">启用状态</span>
        <el-select
          v-model="searchQuery.enable_flag"
          placeholder="请选择启用状态"
          clearable
        >
          <el-option label="启用" value="Y"></el-option>
          <el-option label="禁用" value="N"></el-option>
        </el-select>
      </div>

      <div class="search-item">
        <span class="search-label">业务类型</span>
        <el-select
          v-model="searchQuery.qc_types"
          placeholder="请选择业务类型"
          clearable
        >
          <el-option
            v-for="item in qcTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      
      <div class="search-buttons">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="openDialog('add')">新增</el-button>
      <el-button 
        type="danger" 
        :disabled="selectedIndexes.length === 0"
        @click="batchDelete"
      >
        批量删除({{ selectedIndexes.length }})
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-box">
      <el-table 
        ref="indexTable"
        :data="indexList" 
        border 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="55"
          :selectable="selectable"
        ></el-table-column>
        <el-table-column prop="template_code" label="方案编号" min-width="150"></el-table-column>
        <el-table-column prop="template_name" label="方案名称" min-width="150"></el-table-column>
        <el-table-column prop="qc_types" label="检测种类" min-width="150">
          <template slot-scope="scope">
            {{ formatQcTypes(scope.row.qc_types) }}
          </template>
        </el-table-column>
        <el-table-column prop="enable_flag" label="是否启用" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.enable_flag === 'Y' ? 'success' : 'danger'">
              {{ scope.row.enable_flag === 'Y' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click.stop="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click.stop="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="info" @click.stop="handleView(scope.row)">详细</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-box">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        :current-page.sync="current"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 弹窗表单 -->
    <qc-template-form
      :visible="dialogVisible"
      :is-edit-mode="isEditMode"
      :form-data="formData"
      @update:visible="handleDialogVisibleChange"
      @success="handleFormSuccess"
    />
    
    <!-- 详情弹窗 -->
    <qc-template-detail
      :visible.sync="detailVisible"
      :detail="currentDetail"
      @update:visible="val => detailVisible = val"
      @close="handleDetailClose" 
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import QcTemplateForm from './QcTemplateForm.vue'
import { deleteQcTemplate } from '@/api/qc/QualitySchemeOrder';
import QcTemplateDetail from './QcTemplateDetail.vue';

// 检测种类映射
const QC_TYPE_MAP = {
  '1': '自制工序检验',
  '2': '首检',
  '3': '巡检',
  '4': '来料检验',
  '5': '成品检验',
  '6': '生产退料检验',
  '7': '销售退货检验',
  '8': '出货检验'
};

export default {
  components: {
    QcTemplateForm,
    QcTemplateDetail
  },
  data() {
    return {
      qcTypeOptions: Object.entries(QC_TYPE_MAP).map(([value, label]) => ({
        value,
        label
      })),
      currentDetail: null,
      detailVisible: false,
      currentTemplateId: null,
      isEditMode: false,
      searchQuery: {
        template_code: '',
        template_name: '',
        enable_flag: null,
        qc_types: ''
      },
      indexList: [],
      selectedIndexes: [],
      total: 0,
      current: 1,
      size: 10,
      loading: false,
      dialogVisible: false,
      dialogTitle: '添加检测方案',
      formData: {
        template_id: null,
        template_code: '',
        template_name: '',
        qc_types: [],
        enable_flag: 'Y',
        remark: ''
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    // 格式化检测种类显示
    formatQcTypes(qcTypes) {
      if (!qcTypes) return '-';
      
      // 处理字符串或数组格式
      const typesArray = Array.isArray(qcTypes) 
        ? qcTypes 
        : String(qcTypes).split(',');
      
      return typesArray
        .map(type => QC_TYPE_MAP[type.trim()] || type)
        .filter(Boolean)
        .join(', ') || '-';
    },
    
    async initPage() {
      try {
        this.loading = true
        await this.fetchIndexList()
      } catch (error) {
        this.handleApiError(error, '数据加载失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchIndexList() {
      try {
        this.loading = true
        
        // 构建查询参数，分离分页信息和业务查询参数
        const queryParams = {
          // 普通查询条件
          template_code: this.searchQuery.template_code || undefined,
          template_name: this.searchQuery.template_name || undefined,
          enable_flag: this.searchQuery.enable_flag || undefined,
          qc_types: this.searchQuery.qc_types || undefined
        }
        
        console.log('分页请求参数:', JSON.stringify({
          ...queryParams,
          pageNum: this.current,
          pageSize: this.size
        }, null, 2));

        const response = await request({
          url: '/ldzl-qc/qc/qcTemplate/selectQcTemplateList',
          method: 'post',
          data: queryParams,
          // 分页参数通过 params 传递 (URL参数)
          params: {
            pageNum: this.current,
            pageSize: this.size
          },
          // 禁用防重复提交，因为分页操作会频繁调用
          headers: {
            repeatSubmit: false
          }
        });
        
        if (response.code !== 200) {
          throw new Error(response.data.message || '获取检测方案列表失败')
        }
        
        // 保留原始qc_types格式
        this.indexList = response.rows || [];
        this.total = response.total || 0
        
        console.log('分页响应:', { 
          total: this.total,
          size: this.size,
          current: this.current,
          rows: this.indexList.length,
          // 添加首条记录信息用于调试
          firstRow: this.indexList.length > 0 ? this.indexList[0].template_code : null
        });
        
        this.selectedIndexes = []
      } catch (error) {
        this.handleApiError(error, '检测方案列表加载失败')
      } finally {
        this.loading = false
      }
    },
    
    handleDialogVisibleChange(val) {
      this.dialogVisible = val
      if (!val) {
        this.detailVisible = false
      }
    },
    
    handleSearch() {
      this.current = 1
      this.fetchIndexList()
    },
    
    handleReset() {
      this.searchQuery = {
        template_code: '',
        template_name: '',
        enable_flag: null,
        qc_types: ''
      }
      this.current = 1
      this.fetchIndexList()
    },
    
    handleSelectionChange(val) {
      this.selectedIndexes = val
    },
    
    handleDetailClose() {
      this.detailVisible = false
      this.currentDetail = null
    },
    
    batchDelete() {
      if (this.selectedIndexes.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      
      this.$confirm(`确定删除选中的 ${this.selectedIndexes.length} 条记录吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedIndexes.map(item => item.template_id)
          
          const response = await deleteQcTemplate(ids)
          
          if (response && response.code === 200) {
            this.$message.success('批量删除成功')
            this.selectedIndexes = []
            this.fetchIndexList()
          } else {
            throw new Error(response?.msg || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除错误详情:', error)
          this.$message.error(error.message || '批量删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    selectable(row, index) {
      return true
    },
    
    openDialog(mode = 'add', rowData = null) {
      this.detailVisible = false
      this.dialogVisible = true
      this.isEditMode = mode === 'edit'
      this.dialogTitle = this.isEditMode ? '编辑检测方案' : '添加检测方案'
      
      if (this.isEditMode && rowData) {
        // 将qc_types转换为数组格式供表单使用
        const qcTypesArray = rowData.qc_types 
          ? String(rowData.qc_types).split(',').map(item => item.trim())
          : [];
          
        this.formData = {
          template_id: rowData.template_id,
          template_code: rowData.template_code,
          template_name: rowData.template_name,
          qc_types: qcTypesArray,
          enable_flag: rowData.enable_flag,
          remark: rowData.remark || ''
        }
      } else {
        this.formData = {
          template_id: null,
          template_code: '',
          template_name: '',
          qc_types: [],
          enable_flag: 'Y',
          remark: ''
        }
      }
    },
    
    handleEdit(row) {
      this.openDialog('edit', row)
    },
    
    handleView(row) {
      this.currentDetail = { 
        ...row,
        // 添加格式化后的qc_types用于显示
        formattedQcTypes: this.formatQcTypes(row.qc_types)
      };
      this.detailVisible = true;
    },
    
    async handleDelete(row) {
      try {

        // 检查是否启用
        if (row.enable_flag === 'Y') {
          this.$message.warning('启用状态的检测方案不能删除')
          return
        }
        await this.$confirm('确定删除该记录吗?', '提示', {
          type: 'warning'
        })
        
        const response = await deleteQcTemplate([row.template_id])
        
        if (response) {
          this.$message.success('删除成功')
          this.fetchIndexList()
        } else {
          throw new Error(response?.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.handleApiError(error, '删除失败')
        }
      }
    },
    
    handleSizeChange(val) {
      console.log('改变每页显示数量:', val);
      this.size = val
      // 修改每页条数时，通常会重置到第一页
      this.current = 1
      this.$nextTick(() => {
        this.fetchIndexList()
      })
    },
    
    handlePageChange(val) {
      console.log('改变页码:', val);
      this.current = val
      this.$nextTick(() => {
        this.fetchIndexList()
      })
    },
    
    handleFormSuccess() {
      this.fetchIndexList()
    },
    
    handleApiError(error, defaultMsg = '操作失败') {
      console.error('API Error:', error)
      const msg = error.response?.data?.message || error.message || defaultMsg
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped>
.index-container {
  padding: 20px;
  background: #fff;
}

.search-box {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-label {
  min-width: 80px;
  text-align: right;
  padding-right: 10px;
  font-size: 14px;
}

.search-buttons {
  margin-left: 15px;
  margin-bottom: 10px;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-box {
  margin-top: 20px;
}

.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>